﻿#region Header

// Majesty of Omega - The next evolution of macro management space strategy
// 
// Copyright 2007-2009 André Claaßen
// 
// This file is protected by the terms and conditions of the
// Microsoft Community License (Ms-CL 1.1), a copy of which should
// have been distributed along with this software. If not,
// you may find the license information at the following URL:
// 
// http://www.microsoft.com/resources/sharedsource/licensingbasics/communitylicense.mspx

#endregion

#region

using System;
using System.Collections.Generic;
using System.Text;
using Majesty_of_Omega.Config;
using System.Text.RegularExpressions;
using System.Collections;
using DesignByContract;

#endregion

namespace Majesty_of_Omega.Util
{
    /// <summary>
    /// String helper functions
    /// </summary>
    public static class StringHelper
    {
        /// <summary>
        /// This function cleans string, which came out of the xml configuration files.
        /// the main purpose is to clean up the history description of the races.
        /// </summary>
        /// <see cref="RaceModifiersRace.HistoryFormatted"/>
        /// <param name="xmlElement">Text of the xml element</param>
        /// <returns>Trimmed string</returns>
        public static string StrFormatXmlElementString(string xmlElement)
        {
            bool inParagraph = false;

            StringBuilder builder = new StringBuilder(1024);
            foreach (char c in xmlElement.Trim())
            {
                if (!inParagraph)
                {
                    builder.Append(c);
                    if (c == '\n')
                        inParagraph = true;
                }
                else
                {
                    if (!char.IsWhiteSpace(c))
                    {
                        builder.Append(c);
                        inParagraph = false;
                    }
                }
            }
            return builder.ToString();
        }

        /// <summary>
        /// Formatting helper function for history descriptions of races
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string DoubleLineFeeds(string text)
        {
            StringBuilder builder = new StringBuilder();
            foreach (char c in text)
            {
                if (c == '\n')
                    builder.Append(c, 2);
                else
                    builder.Append(c);
            }
            return builder.ToString();
        }

        /// <summary>
        /// Formats a string and replace all placeholders with the given values 
        /// from the argument list.
        /// </summary>
        /// <param name="textWithPlaceholders">The unicode identifier from the xml files</param>
        /// <param name="placeHolderAndValueList">
        /// variable number of arguments pairs, which are depends from the type of the event.
        /// An argument consists of a variable identifier string and the value as object.
        /// <example>
        /// <code>
        /// ReplacePlaceholders("This is turn number %value1% and this is the event text: %value2%!",
        ///                  "value1", _saveGame.TurnNumber, 
        ///                 "value2", "a suprising event text"); 
        /// </code>
        /// The placeholder variables are defined in the SitRepStrings.xml
        /// </example>
        /// </param>
        public static string ReplacePlaceholders(string textWithPlaceholders, params object[] placeHolderAndValueList)
        {
            Dictionary<string, string> values = CreateValueDictionary(placeHolderAndValueList);
            Regex regex = new Regex(@"%?(\w+)%");
            return regex.Replace(textWithPlaceholders, match =>
                                                           {
                                                               string placeholder = match.Groups[1].Value;
                                                               Require.IsTrue(values.ContainsKey(placeholder), 
                                                                        "No value for parameter %" + placeholder + "% found for string: " + textWithPlaceholders);
                                                               return values[placeholder];
                                                           });
        }

        /// <summary>
        /// Creates the value dictionary out of the parameter list
        /// </summary>
        /// <param name="placeHolderAndValueList">The place holder and value list.</param>
        /// <returns></returns>
        private static Dictionary<string, string> CreateValueDictionary(IEnumerable placeHolderAndValueList)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            IEnumerator enumerator = placeHolderAndValueList.GetEnumerator();
            while (enumerator.MoveNext())
            {
                string key = enumerator.Current.ToString();
                if (!enumerator.MoveNext())
                {
                    throw new ArgumentException(
                        string.Format("Illegal arguments of variable placeholder and value arguments given: {0}", placeHolderAndValueList));
                }
                string value = enumerator.Current.ToString();
                dictionary.Add(key, value);
            }
            return dictionary;
        }
    }
}